package netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

/**
 * @ClassName MyClientHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/4/22 13:33
 * @Version 1.0
 **/
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol message) throws Exception {


        int lenth = message.getLenth();
        byte[] count = message.getCount();
        String msg = new String(count, Charset.forName("utf-8"));
        System.out.println("客户端接收到的长度："+lenth);
        System.out.println("客户端接收到的内容："+msg);

        System.out.println("客户端接收到的内容："+(++this.count));


    }

    //发送数据
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //发送十次,模拟 粘包、拆包
        for(int i=1;i<6;i++){

            String msg = "第"+i+"次通知,今晚六点，排位上分！不见不散";

            byte[] bytes = msg.getBytes(Charset.forName("utf-8"));
            int length = bytes.length;

            //创建协议对象
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLenth(length);
            messageProtocol.setCount(bytes);

            //发送
            ctx.writeAndFlush(messageProtocol);

        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
